<?php
namespace Shopmodule\Model;
use Think\Model;
class UserModel{
	public $usernick;
	public $uzuid;
	public $suid;
	public $sid;
	public $curdate; //日历的当前日期
	public $buqianday; //补签日期
	public $buqianjifen = 0; //补签可得积分
	public $buqianjiac = false; //补签是否加成
	public function getShopUser(){
		if($this->usernick){
			$User = M("User");
			$this->uzuid = $User->where("`usernick`='".$this->usernick."'")->getField("`id`");
			if(!$this->uzuid){
				$this->createUser();
			}
			$ShopUser = M("ShopUsers");
			$this->suid = $ShopUser->where("`userid`=".$this->uzuid." AND `sid`=".$this->sid)->getField("`id`");
			if(!$this->suid){
				$this->createShopUser();
			}
		}
	}
	public function createUser(){
		$User = M("User");
		$data = array();
		$data["usernick"]=$this->usernick;
		$data["jointime"]=date("Y-m-d H:i:s",time());
		$this->uzuid = $User->add($data);
		return $this->uzuid;
	}
	public function createShopUser(){
		$ShopUser = M("ShopUsers");
		$data = array();
		$data["sid"]=$this->sid;
		$data["userid"]=$this->uzuid;
		$data["addtime"]=date("Y-m-d H:i:s",time());
		$this->suid = $ShopUser->add($data);
		return $this->suid;
	}
	public function buqian(){
		// 是否跨月：
		if(date("Ym",strtotime($this->buqianday))!=date("Ym")){
			$info["status"]=false;
			$info["msg"]="对不起，不能跨月补签";
			return $info;
		}
		// 是否已补签：
		$this->getShopUser();
		$seed = $this->getCurrentUserSeeds();
		$userseeds = $this->getUserSeeds();
		$Seeds = M("Seeds");
		$isid = $Seeds->where("DATE_FORMAT(`addtime`,'%Y-%m-%d')='".$this->buqianday."' AND `uzuid`=".$this->suid." AND `sid`=".$this->sid." AND (reason=".C("SEEDS_REASON")["qiandao"]["id"]." OR reason=".C("SEEDS_REASON")["buqian"]["id"].")")->limit(1)->getField("id");
		if($isid){
			$info["status"]=false;
			$info["msg"]="这一天您已补签过了！";;
			// $info["msg"].="订单换积分，越换积分越多哦！<input class=\"btn btn-mini btn-info js-dhdh\" type=\"button\" value=\"兑换\">";;
			return $info;
		}
		//是否在补签日历中（利用日历排除不允许的日期。仅类型为2的日期允许补签）
		$this->curdate = $this->buqianday;
		$this->rili();
		$allowbq = false;
		foreach($this->signlist as $sday){
			if(strtotime($sday["date"])==strtotime($this->buqianday) && $sday["signType"]==2){
				$bqday=$sday;
				$allowbq=true;
			}
		}
		if(!$allowbq){
			switch($bqday["signType"]){
				case 1 : $err = "已经签到。"; break;
				case 3 : $err = "已经签到，可以领奖。"; break;
				case 4 : $err = "已经补签。"; break;
				case 5 : $err = "不是本月日期。"; break;
				case 6 : $err = "应当正常签到。"; break;
				default : $err = "不在允许的补签日期范围内。"; break;
			}
			// $err .= "订单换积分，越换积分越多哦！<input class=\"btn btn-mini btn-info js-dhdh\" type=\"button\" value=\"兑换\">";
			$info["status"]=false;
			$info["msg"]="抱歉，补签失败，原因如下：".$err;
			return $info;
		}
		$point = $this->buqianjifen;
		if($this->buqianjiac){//补签按照设置是否获得积分加成
			$morepoint = $this->getMorePoint($seed);
		}else{
			$morepoint = 0;
		}
		$data["seeds"]=array("exp","seeds + ".($point+$morepoint));
		// $data["lastseeds"]=date("Y-m-d H:i:s",time()); 
		// $data["nextseeds"]=$point; 
		$EU = M("ShopUsers");
		$EU->where("`id`=".$seed["id"])->save($data);
		
		$da["uzuid"]=$seed["id"];
		$da["quangity"]=$point+$morepoint;
		$da["nextseeds"]=0;
		$da["addtime"]=$this->buqianday;
		$da["addby"]=1;
		$da["type"]=1;
		$da["reason"]=C("SEEDS_REASON")["buqian"]["id"];
		$da["status"]=1;
		$da["sid"]=$this->sid;
		$Seeds->add($da);
		
		$info["status"]=true;
		$info["point"]=$point+$morepoint;
		$info["msg"]="亲，您补签获得了".$point."积分。";
		if($this->buqianjiac){
		$info["msg"].="您累计兑换订单".($seed["sumpay"]/100)."元，";
		$info["msg"].="同时获得了".$morepoint."的签到加成，";
		}
		// $info["msg"].="订单换积分，越换积分越多哦！<input class=\"btn btn-mini btn-info js-dhdh\" type=\"button\" value=\"兑换\">";
		return $info;
	}
	public function qiandao(){
		$this->getShopUser();
		$seed = $this->getCurrentUserSeeds();
		$userseeds = $this->getUserSeeds();
		if(date("Ymd",strtotime($seed["lastseeds"]))==date("Ymd",time())&&$seed["lastseeds"]){
			$info["status"]=false;
			// $info["msg"]="今天您已签过到，请明天再来！订单换积分，越换积分越多哦！<input class=\"btn btn-mini btn-info js-dhdh\" type=\"button\" value=\"兑换\">";;
			$info["msg"]="今天您已签过到，请明天再来！";;
		}else{
			$point = $this->getPoint($seed,$userseeds);
			$morepoint = $this->getMorePoint($seed);
			$data["seeds"]=array("exp","seeds + ".($point+$morepoint));
			$data["lastseeds"]=date("Y-m-d H:i:s",time());
			$data["nextseeds"]=$point;
			$EU = M("ShopUsers");
			$EU->where("`id`=".$seed["id"])->save($data);
			$nextseeds = intval($userseeds[$point]);
			// $User->execute("update `uz_status` set `all_seeds` = `all_seeds`+".($point+$morepoint));
			
			$Seeds = M("Seeds");
			$da["uzuid"]=$seed["id"];
			$da["quangity"]=$point+$morepoint;
			$da["nextseeds"]=$point;
			$da["addtime"]=date("Y-m-d H:i:s",time());
			$da["addby"]=1;
			$da["type"]=1;
			$da["reason"]=C("SEEDS_REASON")["qiandao"]["id"];
			$da["status"]=1;
			$da["sid"]=$this->sid;
			$Seeds->add($da);
			
			$info["status"]=true;
			$info["point"]=$poin+$morepoint;
			$info["msg"].="亲，您已领取".($point)."积分。";
			$info["msg"].="明天签到可获得".($userseeds[$point]+$morepoint)."种子！";
			// $info["msg"].="您累计兑换订单".($seed["sumpay"]/100)."元，";
			$info["msg"].="同时获得了".$morepoint."的签到加成，";
			// $info["msg"].="订单换积分，越换积分越多哦！<input class=\"btn btn-mini btn-info js-dhdh\" type=\"button\" value=\"兑换\">";
		}
		return $info;
	}
	public function rili(){
		$TOOL = M("ToolsStatus");
		$cfg = json_decode($TOOL->where("`sid`=".$this->sid." AND `tool_id`=13")->getField("`cfg`"),true);
		$this->buqianjiac = $cfg["buqianjiac"];
		$this->buqianjifen = $cfg["buqianjifen"];
		// $firstday = date("Y-m-d",strtotime(date("Y-m-01",strtotime($curdate)) . ' -'.($cfg["buqian"]+1).' day'));
		$firstday = date("Y-m-01",strtotime($this->curdate));
		$lastday = date("Y-m-d", strtotime(date("Y-m-01",strtotime($this->curdate)) . ' +1 month -1 day'));
		$firstbuqian = null; 
		if($cfg["buqian"] && date("Ym",strtotime($this->curdate))==date("Ym")){
			// 是当前月份时显示补签按钮
			$t = time();
			for($i=1;$i<$cfg["buqian"];$i++){
				// 发现可以补签的日期。从即日起向过去推断。
				$buqian[]=date("Y-m-d",$t-(3600*24*$i));
				if($i+1==$cfg["buqian"]){
					$firstbuqian = $t-(3600*24*($i+2));//记录允许补签的最早日期
				}
			}
		}
		$alldays = (strtotime($lastday)-strtotime($firstday))/(3600*24); //计算取出的天数
		for($i=0;$i<=$alldays;$i++){
			// 生成用于比较的日期列表，计算连续签到
			$cpdays[]=date("Y-m-d",strtotime($firstday)+($i*3600*24));
		}
		$SVIEW = D("Shopmodule/UserseedsView");
		$uwh=$this->usernick?" AND smuser.usernick='".$this->usernick."'":"";
		$vwh=$this->suid?" AND suser.id=".$this->suid:"";
		$days = $SVIEW->where("seeds.sid=".$this->sid.$uwh.$vwh." AND seeds.addtime>='$firstday' AND seeds.addtime<='$lastday' AND (seeds.reason=".C("SEEDS_REASON")["qiandao"]["id"]." OR seeds.reason=".C("SEEDS_REASON")["buqian"]["id"].")")->getField("DATE_FORMAT(seeds.addtime,'%Y-%m-%d') AS addtime,type,reason");
		// echo $SVIEW->_sql();
		$signlist = Array();
		foreach($days as $k=>$day){
			// 读取已签到日期
			if(date("Ym",strtotime($day["addtime"]))==date("Ym",strtotime($this->curdate))){
				unset($arr);
				$arr["date"]=date("Y-m-d",strtotime($day["addtime"]));
				$arr["signDay"]=date("j",strtotime($day["addtime"]));
				if(date("Ym",strtotime($this->curdate)) == date("Ym")){
					// 本月显示补签和签到
					$arr["signType"]=$day["reason"];
				}else{
					// 非本月显示历史签到
					$arr["signType"]=5;
				}
				$signlist[]=$arr;
				foreach($buqian as $j=>$bu){
					// 从补签日期中删除已签到的日期
					if($bu==date("Y-m-d",strtotime($day["addtime"]))){
						unset($buqian[$j]);
					}
				}
			}
		}
		// 统计连续签到的次数 $arrlianxu 数组，存储每次连续签到的数据，其中最长的一条为准
		$arrlianxu = $this->getLianxu($cpdays,$signlist,Array(1,4));
		
		if(isset($arrlianxu)){// 有过签到活动才可以补签
			foreach($arrlianxu as $lianxu){
				if(strtotime($lianxu["enddate"])>=($firstbuqian)){
					$allowbuqian[]=strtotime($lianxu["enddate"]);
				}
			}
			foreach($buqian as $bu){// 增加显示补签日期
				// 当前月份并且在允许的补签范围内才显示补签按钮
				$butime = strtotime($bu);
				if(date("Ym",strtotime($this->curdate))==date("Ym",$butime) && $allowbuqian && $butime > min($allowbuqian)){
					unset($arr);
					$arr["date"]=$bu;
					$arr["signDay"]=date("j",strtotime($bu));
					$arr["signType"]=2;
					$signlist[]=$arr;
				}
			}
		}
		
		foreach($signlist as $list){
			if($list["date"]==date("Y-m-d")){
				$todaysigned=true;
			}
		}
		// 在当前日期显示“签到”按钮
		if(!$todaysigned && date("Ym")==date("Ym",strtotime($this->curdate))){
			unset($s);
			$s["date"]=date("Y-m-d");
			$s["signDay"]=date("j");
			$s["signType"]=6;
			$signlist[]=$s;
		}
		//连续签到兑换奖品
		if(date("Ym")==date("Ym",strtotime($this->curdate)) && $cfg["onoff_qddh"]==1){
			$arrlianxu = $this->getLianxu($cpdays,$signlist,Array(1,2,4));
			$giftday = $arrlianxu[0]["startdate"];
			foreach($cfg["qddh"] as $qddh){
				if($qddh["gift"]>0){
					$giftdays[] = $d = date("Y-m-d",strtotime($giftday ." +".$qddh["tian"]." day"));
					$hasday = false;
					foreach($signlist as $k=>$lst){
						if($lst["date"]==$d){
							$hasday=true;
							$signlist[$k]["giftDay"] = 1;
							$signlist[$k]["giftId"] = $qddh["gift"];
						}
					}
					if(!$hasday){
						unset($s);
						$s["date"]=$d;
						$s["signDay"]=date("j",strtotime($d));
						$s["giftDay"]=2;
						$s["giftId"] = $qddh["gift"];
						$signlist[] = $s;
					}
				}
			}
		}
		$this->signlist=$signlist;
	}
	public function getCurrentUserSeeds(){
		$ShopUser = M("ShopUsers");
		$seeds = current($ShopUser->where("`id`=".$this->suid)->getField("id,id,userid,nextseeds,seeds,sumpay"));
		$SEEDS = M("Seeds");
		$seeds["lastseeds"] = $SEEDS->where("`uzuid`=".$this->suid." AND `sid`=".$this->sid." AND (`reason`=1 OR `reason`=4)")->order("`addtime` DESC")->limit(1)->getField("addtime");
		return $seeds;
	}
	public function getUserSumpay(){
		$ShopUser = M("ShopUsers");
		$sumpay = $ShopUser->where("`id`=".$this->suid)->getField("sumpay");
		return $sumpay/100;
	}
	// 获取连续签到数据
	private function getLianxu($cpdays,$signlist,$type){
		$lxqd=0;
		foreach($cpdays as $cpday){
			$lianxu = false;
			foreach($signlist as $sday){
				if($cpday==$sday["date"] && in_array($sday["signType"],$type)){
					$lianxu=true;
					if(!$firstsignday){
						$firstsignday=$cpday;
					}
				}
			}
			if($lianxu){
				$lxqd++;
			}else{
				if($lxqd>0){
					unset($arr);
					$arr["days"]=$lxqd;
					$arr["startdate"]= date("Y-m-d",strtotime($cpday." -".$lxqd." day"));
					$arr["enddate"]=date("Y-m-d",strtotime($cpday." -1 day"));
					$arrlianxu[]=$arr;
					$lxqd=0;
				}
			}
		}
		return array_reverse($arrlianxu);
	}
	private function getUserSeeds(){
		$CFG = M("ToolsStatus");
		$cfg = json_decode($CFG->where("`tool_id`=13 AND `sid`=".$this->sid)->getField("cfg"),true);
		$i=0;
		foreach($cfg["day"] as $k=>$key){
			if($k==0){
				$userseeds[0] = $key; 
			}
			$userseeds[$key] = $cfg["day"][$k+1]; 
			$i++;
		}
		$userseeds[$cfg["day"][$i-1]]=$cfg["day"][$i-1];
		return $userseeds;
	}
	private function getPoint($seed,$userseeds){
		$Yesterday = date('Ymd',time()-3600*24);
		if($Yesterday==date("Ymd",strtotime($seed['lastseeds']))){
			$point = intval($userseeds[$seed['nextseeds']]); 
		}else{
			$point = intval($userseeds[0]); 
		}
		if(empty($point)){
			$point = intval($userseeds[0]); 
		}
		return $point;
	}
	private function getMorePoint($seed){
		$morepoint = 0;
		$next=false;
		$TOOL = M("ToolsStatus");
		$cfg = json_decode($TOOL->where("`sid`=".$this->sid." AND `tool_id`=13")->getField("`cfg`"),true);
		if($cfg && $cfg["jc"]){
			foreach($cfg["jc"] as $k=>$jc){
				$jfjc[$jc["jine"]]= $jc["jifen"];
			}
			ksort($jfjc);
			foreach($jfjc as $je => $jc){
				if($seed["sumpay"]>=$je){
					$morepoint=$jc;
				}
				$msg .= "兑换".$je."元订单，每天签到可额外获得".$jc."积分。";
			}
		}
		return $morepoint;
	}
}